package by.cooker.persdic.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMDictionaryParser {

	private static final DocumentBuilderFactory factory = DocumentBuilderFactory
			.newInstance();

	static {
		factory.setIgnoringComments(true);
		factory.setIgnoringElementContentWhitespace(true);
		factory.setCoalescing(true);
	}

	public void parseFile(File file) throws SAXException, IOException,
			ParserConfigurationException {
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(file);

		NodeList dictionaryList = doc.getElementsByTagName("dictionary");
		NodeList wordList = doc.getElementsByTagName("word");

		System.out.println("Start parsing...");

		Node dicName = dictionaryList.item(0);
		NamedNodeMap dicNameAttrs = dicName.getAttributes();

		System.out.println("Dictionary name: "
				+ dicNameAttrs.item(0).getNodeValue());

		System.out.println("Dictionary staff: ");

		for (int i = 0; i < wordList.getLength(); i++) {
			Node node = wordList.item(i);

			System.out.println("Word id: "
					+ node.getAttributes().item(0).getNodeValue());

			if (node.hasChildNodes()) {
				System.out.println("Childs count: " + node.getChildNodes().getLength());
//				NodeList childNodes = node.getChildNodes();
//
//				for (int j = 0; j < childNodes.getLength(); j++) {
//					System.out.println(childNodes.item(j).getNodeValue());
//				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		DOMDictionaryParser dp = new DOMDictionaryParser();
		dp.parseFile(new File("programming.dic.xml"));
	}
}
